﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class GunComponent : NetworkBehaviour
{
    public GameObject playerCamera;
    public Transform bulletPos;
    public Animator animatorGun;
    private int bulletNum = 30;
    private int bulletMaxNum = 30;
    private static readonly int Reload1 = Animator.StringToHash("reload");
    private static readonly int IsReload = Animator.StringToHash("IsReload");

    public void OnFire(int num)
    {
        if (playerCamera == null)
        {
            return;
        }

        if (bulletNum <= 0)
        {
            Debug.Log("没有子弹了");
            return;
        }

        if (animatorGun.GetBool(IsReload))
        {
            return;
        }

        var origin = playerCamera.transform.position;
        var direction = playerCamera.transform.forward;

        RaycastHit hit;
        if (Physics.Raycast(origin, direction, out hit, 1000)) {
            //生成子弹，弹坑，特效
            Vector3 dir = hit.point - bulletPos.position;
            CmdDoFire(bulletPos.position, dir);
            bulletNum--;
            if (isLocalPlayer)
            {
                Game.UI.GetUI<UI_Battle>().SetBulletNum(bulletNum,bulletMaxNum);
            }
            bool isLayer = hit.transform.gameObject.layer == LayerMask.NameToLayer("Player");
            if (isLayer)
            {
                if (hit.transform.gameObject.GetComponent<Actor>())
                {
                    Actor target = hit.transform.gameObject.GetComponent<Actor>();
                    Game.GetComp<ActorManager>().GetActor(netId.Value).propertyComponent.CmdTakeDamage(target.networkId, num);
                }
            }
        }
    }
    
    [Command]
    public void CmdDoFire(Vector3 bulletPos,Vector3 dir)
    {
        GameObject go = Instantiate(Resources.Load<GameObject>("Bullet"), bulletPos, Quaternion.LookRotation(dir));
        NetworkServer.Spawn(go);
        Destroy(go, 3);
    }

    public void ReloadAnim()
    {
        animatorGun.SetTrigger(Reload1);
    }
    
    public void Reload()
    {
        if (!animatorGun.GetBool(IsReload))
        {
            CmdDReload(netId.Value);
        }
    }

    [Command]
    public void CmdDReload(uint id)
    {
        RpcReload(id);
    }
    
    [ClientRpc]
    void RpcReload(uint id)
    {
        Game.GetComp<ActorManager>().Reload(id);
    }
    
    public void SetAnimCallBack()
    {
        animatorGun.GetBehaviour<GunAnimBehaviour>().callBack = () =>
        {
            bulletNum = bulletMaxNum;
            if (isLocalPlayer)
            {
                Game.UI.GetUI<UI_Battle>().SetBulletNum(bulletNum,bulletMaxNum);
            }
        };
    }
}
